<?php


namespace Drupal\shusy_store_order_line\ViewsController\handler\field;


use Drupal\shusy_store_order\Entity\ShusyStoreOrder;
use Drupal\shusy_store_order_line\Entity\ShusyStoreOrderLine;
use views_handler_field_entity;

class ShusyStoreOrderLineLinesViewsField extends views_handler_field_entity {

  function option_definition() {
    $options = parent::option_definition();
    $options['view'] = ['default' => ''];
    return $options;
  }

  function options_form(&$form, &$form_state) {
    $options = [];
    foreach (views_get_all_views() as $name => $view) {
      if ($view->base_table == 'shusy_store_order_line') {
        foreach ($view->display as $display_name => $display) {
          $options[check_plain($name)][$name . '|' . $display_name] = $display->display_title;
        }
      }
    }
    $form['view'] = [
      '#type' => 'select',
      '#title' => t('Order contents View'),
      '#description' => t('Specify the View to use to display the line items referenced by this field.'),
      '#options' => $options,
      '#default_value' => $this->options['view'],
    ];
    parent::options_form($form, $form_state);
  }

  function render($values) {
    //    dpm($this->options);
    [$view_id, $display_id] = explode('|', $this->options['view']);
    if ($entity = $this->get_value($values)) {
      if ($entity instanceof ShusyStoreOrder) {
        $lines = shusy_store_order_line_load_multiple(FALSE, ['store_order_id' => $entity->id]);
        $ids = [];
        foreach ($lines as $line) {
          if ($line instanceof ShusyStoreOrderLine) {
            $ids[] = $line->id;
          }
        }

        //        dpm($view_id);
        //        dpm($display_id);
        $view = views_get_view($view_id);
        $view->set_display($display_id);
        $view->set_arguments($ids);
        if (!empty($override_url)) {
          $view->override_url = $override_url;
        }
        $view->pre_execute();
        $view->execute();
        return $view->render();
      }
    }
  }
}
